﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using RearLivestock.Common.Domains.hq;
using RearLivestock.Common.Dtos;
using RearLivestock.Common.Infrastructure.Interface;
using RearLivestock.Common.Infrastructure.Repositories;
using RearLivestock.RBAC.Api.Application.hqApplication.Commands.Enterprisess;
using RearLivestock.RBAC.ErrorCodeEnum;
using System.Formats.Asn1;

namespace RearLivestock.RBAC.Api.Application.hqApplication.Commands.PigBabyss
{
    public class ShowPigHander : IRequestHandler<ShowPigCommand, Result<PageResultDto<PigBayassesDto>>>
    {
        private readonly IMapper mapper;

        private readonly IBaseRepository<PigBabys> pigBabysRepository;

        public readonly IBaseRepository<Bedrooms> bedroomsrepository;

        public ShowPigHander(IMapper mapper, IBaseRepository<PigBabys> pigBabysRepository, IBaseRepository<Bedrooms> bedroomsrepository)
        {
            this.mapper = mapper;
            this.pigBabysRepository = pigBabysRepository;
            this.bedroomsrepository = bedroomsrepository;

        }
        public async Task<Result<PageResultDto<PigBayassesDto>>> Handle(ShowPigCommand request, CancellationToken cancellationToken)
        {
            var result = new Result<PageResultDto<PigBayassesDto>>() { Code = (int)CommonErrorCode.Search };
            var page = new PageResultDto<PigBayassesDto>() { List = new List<PigBayassesDto>(), PageCount = 0, TotalCount = 0 };
            var pigb = await (from p in await pigBabysRepository.GetAll()
                              join b in await bedroomsrepository.GetAll()
                              on p.BedroomId equals b.BedroomId
                              select new PigBayassesDto()
                              {
                                  PigId = p.PigId,
                                  PigNo = p.PigNo,
                                  PigTime = p.PigTime,
                                  Pigear = p.Pigear,
                                  BedroomId = p.BedroomId,
                                  PigClass = p.PigClass,
                                  Pigweight = p.Pigweight,
                                  BedroomName = b.BedroomName
                              }).ToListAsync();

            page.PageCount = (int)Math.Ceiling(page.TotalCount * 1.0 / request.PageSize);
            page.TotalCount = pigb.Count();
            page.List = pigb.OrderBy(x => x.PigId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
            result.Data = page;
            result.Code = (int)CommonErrorCode.Success;
            return result;
        }


    }
}
